package javabasic.threads;

public class UnsafeThread {
    public static void main(String[] args) {
        TicketWindow ticketWindow = new TicketWindow();
        Thread thread = new Thread(ticketWindow,"窗口一");
        Thread thread1 = new Thread(ticketWindow, "窗口二");
        Thread thread2 = new Thread(ticketWindow, "窗口三");
        Thread thread3 = new Thread(ticketWindow, "窗口四");
        thread.start();
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

class TicketWindow implements Runnable{
    private int ticket=10;
    private Object lock=new Object();

    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (!getTicket()){
                break;
            }
        }
    }

    private synchronized boolean getTicket(){
        //同步代码块保证线程安全
        //synchronized (lock){
        //    if (this.ticket>0){
        //        System.out.println(Thread.currentThread().getName()+"卖出去的票为："+this.ticket--);
        //        return true;
        //    }else {
        //        return false;
        //    }
        //}

        //方法加synchronize关键字相当于给当前实例加锁，然后将方法中的逻辑移动到代码块中  当然如果是静态方法使用synchronize同步，相当于给当前类对象加锁
        //synchronized (this){}
        if (this.ticket>0){
            System.out.println(Thread.currentThread().getName()+"卖出去的票为："+this.ticket--);
            return true;
        }else {
            return false;
        }
    }
}
